const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');

// 测试函数
async function testConnections() {
    console.log('开始测试网络连接...\n');
    
    // 测试目标列表
    const targets = [
        { name: '后端根路径', url: 'http://localhost:8080' },
        { name: '验证码接口', url: 'http://localhost:8080/auth/sendCode/19852725830' },
        { name: '百度', url: 'https://www.baidu.com' },
        { name: '本地IP测试', url: 'http://127.0.0.1:8080' }
    ];
    
    // 记录结果
    const results = [];
    
    // 依次测试每个目标
    for (const target of targets) {
        console.log(`测试 ${target.name}: ${target.url}`);
        const result = await testConnection(target);
        results.push(result);
        console.log('-----------------------------------');
    }
    
    // 保存结果到文件
    const logFile = path.join(__dirname, 'connection-test-log.txt');
    let logContent = '网络连接测试结果\n' + 
                     '===================\n\n' + 
                     new Date().toLocaleString() + '\n\n';
    
    results.forEach(result => {
        logContent += `${result.name}: ${result.url}\n`;
        logContent += `状态: ${result.success ? '成功' : '失败'}\n`;
        logContent += `响应时间: ${result.responseTime}ms\n`;
        logContent += `状态码: ${result.statusCode || 'N/A'}\n`;
        logContent += `错误: ${result.error || '无'}\n`;
        logContent += '\n';
    });
    
    fs.writeFileSync(logFile, logContent);
    console.log(`\n测试完成！详细日志已保存至: ${logFile}`);
}

// 单个连接测试函数
function testConnection(target) {
    return new Promise(resolve => {
        const result = {
            name: target.name,
            url: target.url,
            success: false,
            responseTime: 0,
            statusCode: null,
            error: null
        };
        
        const startTime = Date.now();
        const isHttps = target.url.startsWith('https://');
        const client = isHttps ? https : http;
        const url = new URL(target.url);
        
        const options = {
            hostname: url.hostname,
            port: url.port || (isHttps ? 443 : 80),
            path: url.pathname + url.search,
            method: 'GET',
            headers: {
                'isToken': 'false',
                'User-Agent': 'Node.js Test Client'
            },
            timeout: 10000 // 10秒超时
        };
        
        const req = client.request(options, (res) => {
            result.statusCode = res.statusCode;
            result.success = res.statusCode >= 200 && res.statusCode < 300;
            result.responseTime = Date.now() - startTime;
            
            console.log(`状态码: ${res.statusCode}`);
            console.log(`响应时间: ${result.responseTime}ms`);
            console.log('响应头:', res.headers);
            
            // 收集响应体（限制大小）
            let responseBody = '';
            res.on('data', (chunk) => {
                if (responseBody.length < 1000) { // 限制响应体大小
                    responseBody += chunk;
                }
            });
            
            res.on('end', () => {
                if (responseBody.length > 0) {
                    console.log('响应体前1000字符:', responseBody.substring(0, 1000));
                }
                resolve(result);
            });
        });
        
        req.on('error', (e) => {
            result.error = e.message;
            result.responseTime = Date.now() - startTime;
            console.error(`请求错误: ${e.message}`);
            resolve(result);
        });
        
        req.on('timeout', () => {
            result.error = '请求超时';
            result.responseTime = Date.now() - startTime;
            console.error('请求超时');
            req.abort();
        });
        
        req.end();
    });
}

// 执行测试
console.log('Node.js版本:', process.version);
console.log('操作系统:', process.platform);
console.log('架构:', process.arch);

// 测试本地8080端口是否开放
const net = require('net');
const socket = new net.Socket();

socket.setTimeout(2000);

socket.on('connect', () => {
    console.log('\n检测到本地8080端口已开放！');
    socket.destroy();
    testConnections();
});

socket.on('timeout', () => {
    console.log('\n未检测到本地8080端口开放。可能的原因：');
    console.log('1. 后端服务未启动');
    console.log('2. 防火墙阻止了连接');
    console.log('3. 端口不是8080');
    socket.destroy();
    testConnections(); // 仍然执行完整测试
});

socket.on('error', (err) => {
    console.log('\n端口检测错误:', err.message);
    testConnections(); // 仍然执行完整测试
});

socket.connect(8080, 'localhost');